from os import listdir,chdir,system,mkdir
from os.path import join,isdir,exists
from functools import partial
from utils.cry import unzip
from subprocess import PIPE, Popen
def getusb():
    with Popen("df",shell=True,stdout=PIPE) as p:
        out=p.stdout
        for ln in out.readlines():
            lns=ln.decode()[0:-1]
            if "/media/shuaihu/" in lns:
                s= lns.split(' ')
                return s[0],s[-1]
        else:
            return None,None

def backup_jpg(spath,path):
    def getjpgpath(path):
        i=0
        ffd=""
        for i in range(0,999):
            fd="jpg{:03d}".format(i)
            ffd=join(path,fd)
            i+=1
            if not exists(ffd):
                mkdir(ffd)
                break
        else:
            return None
        return ffd
    
    cmd="mv {} {}"
    files=listdir(spath)
    if len(files)>0 :
        dpath=getjpgpath(path)
        if dpath:
            system(cmd.format(spath+"/*",dpath))

def update(curdir):
    dev,path=getusb()
    result=False
    if not dev: return False
    backup_jpg(join(curdir,"jpg"),path)

    pkg=join(path,"updatepkg.tar.bz2")
    if  exists(pkg):
        if "objectdetector" in curdir:
            cmd=f"rm {curdir}/* -rf"
            system(cmd)
        unzip(pkg,curdir)
        result=True
    system(f"udisksctl unmount -b {dev} >/dev/null")
    system(f"udisksctl power-off -b {dev} >/dev/null")
    return result
